package com.candy.security.jwt.weixin;

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import static com.candy.security.jwt.service.CustomUserDetailsService.UsernameSplit;

@AllArgsConstructor
public class WeixinCodeAuthenticationProvider implements AuthenticationProvider
{
	@Autowired
	private UserDetailsService userDetailsService;

	/**
	 *   进行身份认证的逻辑
	 * @param authentication
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException
	{
		WeixinCodeAuthenticationToken authenticationToken = (WeixinCodeAuthenticationToken)authentication;
		if(authenticationToken.getPrincipal()==null)
		{
			throw new InternalAuthenticationServiceException("微信验证码获取失败");
		}
		UserDetails user = userDetailsService.loadUserByUsername(authenticationToken.getPrincipal()+UsernameSplit+"weixin_openid");
		if (user == null) {
			throw new InternalAuthenticationServiceException("您的微信未与系统账号绑定，请联系管理人员");
		}
		UsernamePasswordAuthenticationToken authenticationResult = new UsernamePasswordAuthenticationToken(user, user.getAuthorities());
		authenticationResult.setDetails(authenticationToken.getDetails());
		return authenticationResult;
	}

	/**
	 *  根据该方法判断 AuthenticationManager选择哪个 Provider进行认证处理
	 * @param authentication
	 * @return
	 */
	@Override
	public boolean supports(Class<?> authentication) {
		return WeixinCodeAuthenticationToken.class.isAssignableFrom(authentication);
	}
}

